#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import requests, time, datetime, pymysql
from django.conf import settings
from fpdf import FPDF
from random import randint

from orders.models import OrderInfo, OrderGoods
from merchants.models import MerchantBill, MerchantMonthlyBill, Merchant
from equity_mall.utils.qiniu_storage import pic_upload


def create_monthly_bill():
    print('%s: create_monthly_bill' % time.ctime())
    today = datetime.datetime.now()
    first_day = today.replace(day=1)
    last_month = first_day - datetime.timedelta(days=1)
    last_month_first_day = last_month.strftime('%Y-%m-01 00:00:00')
    last_month_last_day = last_month.strftime('%Y-%m-%d 23:59:59')
    conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                           port=settings.DATABASES['default']['PORT'],
                           database=settings.DATABASES['default']['NAME'],
                           user=settings.DATABASES['default']['USER'],
                           password=settings.DATABASES['default']['PASSWORD'])
    cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
    sql = f'SELECT merchant_id,GROUP_CONCAT(id) AS bill_id_list,SUM(settlement_amount)AS settlement_amount,MAX(level_id)AS level_id FROM tb_merchant_bill WHERE bill_state=3 AND point=0 AND settlement_time >= "{last_month_first_day}" AND settlement_time <= "{last_month_last_day}" GROUP BY merchant_id;'
    cursor.execute(sql)
    rows = cursor.fetchall()
    cursor.close()
    conn.close()
    for row in rows:
        merchant_id = row['merchant_id']
        bill_id_list = row['bill_id_list']
        settlement_amount = row['settlement_amount']
        level_id = row['level_id']
        orderinfo_set = OrderInfo.objects.filter(bill_id__in=bill_id_list.split(','))
        monthly_bill_data = {}
        monthly_bill_data['merchant_id'] = merchant_id
        monthly_bill_data['receipts_time'] = last_month_first_day
        monthly_bill_data['bill_name'] = f'{last_month.strftime("%Y年%m月")}结算账单'
        monthly_bill_data['bill_time'] = f'{last_month.strftime("%Y年%m月01日")}-{last_month.strftime("%d日")}'
        monthly_bill_data['order_amount'] = settlement_amount
        monthly_bill_data['order_count'] = len(orderinfo_set)
        monthly_bill_data['separate_amount'] = 0
        monthly_bill_data['restitution_amount'] = 0
        monthly_bill_data['settlement_amount'] = settlement_amount
        monthly_bill_data['level_id'] = level_id
        monthly_bill, create = MerchantMonthlyBill.objects.get_or_create(defaults=monthly_bill_data, receipts_time=last_month_first_day, merchant_id=merchant_id)
        if create:
            orderinfo_set.update(monthly_bill_id=monthly_bill.id)
            merchant = Merchant.objects.get(id=merchant_id)
            pdf = FPDF()
            pdf.add_page()
            fname1 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), f'static/fonts/LXGWNeoZhiSongCHS.ttf')
            fname2 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), f'static/fonts/WenQuanYiMicroHei.ttf')
            pdf.add_font('LXGWNeoZhiSongCHS', style='', fname=fname1, uni=True)
            pdf.add_font('WenQuanYiMicroHei', style='', fname=fname2, uni=True)
            pdf.set_font("WenQuanYiMicroHei", size=10)
            pdf.cell(w=190, h=8, txt='', border=0, ln=1, align="C")
            pdf.cell(w=190, h=8, txt='', border=0, ln=1, align="C")
            pdf.cell(w=190, h=8, txt=monthly_bill.bill_name, border=1, ln=1, align="C")
            pdf.set_font("LXGWNeoZhiSongCHS", size=10, style='U')
            pdf.cell(w=190, h=8, txt=f'致  {merchant.name}    ：', border=1, ln=1, align="L")
            pdf.set_font("LXGWNeoZhiSongCHS", size=10)
            pdf.cell(w=190, h=8, txt=f'   以下为{last_month.strftime("%Y年%m月")}商圈订单结算账单，以下是账单详情。    ', border=1, ln=1, align="L")
            pdf.set_font("WenQuanYiMicroHei", size=10)
            pdf.cell(w=90, h=8, txt='结算时间', border=1, ln=0, align="L")
            pdf.set_font("LXGWNeoZhiSongCHS", size=10)
            pdf.cell(w=100, h=8, txt=monthly_bill.bill_time, border=1, ln=1, align="L")
            pdf.set_font("WenQuanYiMicroHei", size=10)
            pdf.cell(w=90, h=8, txt='应结算订单数量', border=1, ln=0, align="L")
            pdf.set_font("LXGWNeoZhiSongCHS", size=10)
            pdf.cell(w=100, h=8, txt=f'{monthly_bill.order_count}笔', border=1, ln=1, align="L")
            pdf.set_font("WenQuanYiMicroHei", size=10)
            pdf.cell(w=90, h=8, txt='应结算订单金额', border=1, ln=0, align="L")
            pdf.set_font("LXGWNeoZhiSongCHS", size=10)
            pdf.cell(w=100, h=8, txt=f'￥{monthly_bill.order_amount}', border=1, ln=1, align="L")
            pdf.set_font("WenQuanYiMicroHei", size=10)
            pdf.cell(w=90, h=8, txt='分账结算（1%）', border=1, ln=0, align="L")
            pdf.set_font("LXGWNeoZhiSongCHS", size=10)
            pdf.cell(w=100, h=8, txt='-￥0.00', border=1, ln=1, align="L")
            pdf.set_font("WenQuanYiMicroHei", size=10)
            pdf.cell(w=90, h=8, txt='平台返还结算（1%）', border=1, ln=0, align="L")
            pdf.set_font("LXGWNeoZhiSongCHS", size=10)
            pdf.cell(w=100, h=8, txt='+￥0.00', border=1, ln=1, align="L")
            pdf.set_font("WenQuanYiMicroHei", size=10)
            pdf.cell(w=90, h=8, txt='应结算费用总计', border=1, ln=0, align="L")
            pdf.set_font("LXGWNeoZhiSongCHS", size=10)
            pdf.cell(w=100, h=8, txt=f'￥{monthly_bill.order_amount}', border=1, ln=1, align="L")
            pdf.cell(w=190, h=8, txt='*注：以上应结算金额未扣除交易手续费，具体结算金额以实际到账为准。', border=1, ln=1, align="L")
            pdf.set_font("WenQuanYiMicroHei", size=10)
            pdf.cell(w=190, h=8, txt='具体已结算订单明细', border=1, ln=1, align="C")
            pdf.cell(w=50, h=8, txt='订单编号', border=1, ln=0, align="C")
            pdf.cell(w=30, h=8, txt='商品名称', border=1, ln=0, align="C")
            pdf.cell(w=20, h=8, txt='商品数量', border=1, ln=0, align="C")
            pdf.cell(w=30, h=8, txt='下单时间', border=1, ln=0, align="C")
            pdf.cell(w=30, h=8, txt='结算时间', border=1, ln=0, align="C")
            pdf.cell(w=30, h=8, txt='应结算金额（元）', border=1, ln=1, align="C")

            pdf.set_font("LXGWNeoZhiSongCHS", size=7)
            a = 14
            for orderinfo in orderinfo_set:
                ordergoods = OrderGoods.objects.filter(order_id=orderinfo.id).first()
                goods = ordergoods.goods
                goods_name_width = pdf.get_string_width(goods.name)
                if goods_name_width <= 30:
                    if a > 32:
                        a = 0
                        pdf.add_page()
                    pdf.cell(w=50, h=8, txt=orderinfo.order_id, border=1, ln=0, align="C")
                    pdf.cell(w=30, h=8, txt=goods.name, border=1, ln=0, align="C")
                    pdf.cell(w=20, h=8, txt=str(ordergoods.count), border=1, ln=0, align="C")
                    pdf.cell(w=30, h=8, txt=orderinfo.create_time.strftime("%Y-%m-%d %H:%M:%S"), border=1, ln=0, align="C")
                    pdf.cell(w=30, h=8, txt=orderinfo.bill.settlement_time.strftime("%Y-%m-%d %H:%M:%S"), border=1, ln=0, align="C")
                    pdf.cell(w=30, h=8, txt=str(orderinfo.payable_settled_amount), border=1, ln=1, align="C")
                    a += 1
                else:
                    if a > 31:
                        a = 0
                        pdf.add_page()
                    y = pdf.get_y()
                    x = pdf.get_x()
                    pdf.multi_cell(w=50, h=8, txt=orderinfo.order_id + '\n ', border=1, align="C")
                    pdf.set_xy(x + 50, y)
                    pdf.multi_cell(w=30, h=8, txt=f'{goods.name}', border=1, align="C")
                    pdf.set_xy(x + 80, y)
                    pdf.multi_cell(w=20, h=8, txt=str(ordergoods.count) + '\n ', border=1, align="C")
                    pdf.set_xy(x + 100, y)
                    pdf.multi_cell(w=30, h=8, txt=orderinfo.create_time.strftime("%Y-%m-%d %H:%M:%S") + '\n ', border=1, align="C")
                    pdf.set_xy(x + 130, y)
                    pdf.multi_cell(w=30, h=8, txt=orderinfo.bill.settlement_time.strftime("%Y-%m-%d %H:%M:%S") + '\n ', border=1, align="C")
                    pdf.set_xy(x + 160, y)
                    pdf.multi_cell(w=30, h=8, txt=str(orderinfo.payable_settled_amount) + '\n ', border=1, align="C")
                    a += 2

            file_name = f"{merchant.name}{monthly_bill.bill_name}{'%06d' % randint(0, 999999)}.pdf"
            path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), f'static/{file_name}')
            pdf.output(path)
            with open(path, 'rb') as f:
                result = f.read()
            pic_upload(result, file_name)
            os.remove(path)
            monthly_bill.bill_file = file_name
            monthly_bill.save()
        print(len(orderinfo_set))
    return '生产账单'


def aaaaa():
    pdf = FPDF()
    pdf.add_page()
    fname1 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                          f'static/fonts/LXGWNeoZhiSongCHS.ttf')
    fname2 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                          f'static/fonts/WenQuanYiMicroHei.ttf')
    pdf.add_font('LXGWNeoZhiSongCHS', style='', fname=fname1, uni=True)
    pdf.add_font('WenQuanYiMicroHei', style='', fname=fname2, uni=True)
    pdf.set_font("WenQuanYiMicroHei", size=7)
    a = pdf.get_string_width('三只松鼠礼遇欢禧礼盒1300g')
    print(a)


if __name__ == '__main__':
    create_monthly_bill()
